package com.mm.fam.web.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.mm.fam.web.base.ResponseModel;
import com.mm.fam.web.base.ResponseUtil;
import com.mm.fam.web.entity.SysRolePermission;
import com.mm.fam.web.mapper.SysPermissionMapper;
import com.mm.fam.web.mapper.SysRolePermissionMapper;
import com.mm.fam.web.service.OperateAccreditService;
import com.mm.fam.web.vo.MenuOperateAccredit;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class OperateAccreditServiceImpl implements OperateAccreditService {

    @Autowired
    SysPermissionMapper sysPermissionMapper;

    @Autowired
    SysRolePermissionMapper sysRolePermissionMapper;

    @Override
    public ResponseEntity<ResponseModel<Object>> queryOperateAccreditList(Integer roleId) {
        ResponseEntity<ResponseModel<Object>> re = null;
        List<MenuOperateAccredit> menuOperateAccredits = sysPermissionMapper.queryOperateAccreditList(roleId);
        List<Object> resultList = new ArrayList<>();

        for(MenuOperateAccredit moa : menuOperateAccredits){
            Map<String, Object> item = new HashMap<>();
            item.put("menuTitle", moa.getTitle());

            String[] ids = moa.getIds().split(",");
            String[] actions = moa.getActions().split(",");
            String[] actionNames = moa.getActionNames().split(",");
            String[] actionStatus = moa.getActionStatus().split(",");

            List<Object> childList = new ArrayList<>();
            for(int i = 0; i < ids.length; i++){
                Map<String, Object> child = new HashMap<>();
                child.put("id", ids[i]);
                child.put("action", actions[i]);
                child.put("actionName", actionNames[i]);
                child.put("status", actionStatus[i]);
                childList.add(child);
            }

            item.put("menuOperationPower", childList);
            resultList.add(item);
        }
        re = ResponseUtil.success(resultList);
        return re;
    }

    @Override
    public ResponseEntity<ResponseModel<Object>> saveRoleOperateAccredit(List<Map<String, Integer>> param) {
        ResponseEntity<ResponseModel<Object>> re = null;
        for(Map<String, Integer> map : param){
            SysRolePermission srp = new SysRolePermission();
            srp.setStatus(map.get("actionStatus"));
            sysRolePermissionMapper.update(srp, new QueryWrapper<SysRolePermission>()
                    .eq("role_id", map.get("roleId"))
                    .eq("perm_id", map.get("actionId")));
        }
        re = ResponseUtil.success(null);
        return re;
    }
}
